<template>
  <div class="logDialog">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleFormRef"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  // unref,
  import { ref, reactive } from 'vue'
  // import { login } from '@/api/login'
  // import { ruleForm } from './hooks/login'
  import { useStoreLogin } from '@/store/userLogin.js'
  import { storeToRefs } from 'pinia'
  import { useRoute, useRouter } from 'vue-router'

  export default {
    setup() {
      const store = useStoreLogin()

      const route = useRoute()
      const router = useRouter()
      const ruleFormRef = ref()

      const ruleForm = reactive({
        name: '',
        password: '',
        vc_token: '',
        auth_type: 'vc',
        flag: '1',
        vc_code: ''
      })

      const rules = reactive({
        name: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 3,
            max: 5,
            message: '长度在 3 到 5 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 5,
            message: '长度在 6 到 10 个字符',
            trigger: 'blur'
          }
        ]
      })

      const { storeLogin } = storeToRefs(store)
      const submitForm = async () => {
        // const form = unref(ruleFormRef)
        ruleFormRef.value.validate((isOK) => {
          if (isOK) {
            // form.resetFields()

            store.storeLogin(ruleForm)
            ElMessage.success('登录成功')
            const redirect = route.query.redirect
            ruleFormRef.value.resetFields()
            if (typeof redirect !== 'string') {
              router.replace({
                name: 'home'
              })
            } else {
              router.replace(redirect)
            }
          }
        })
      }

      const resetForm = () => {
        // const form = unref(ruleFormRef)
        // form.resetFields()
        ruleFormRef.value.resetFields()
      }

      return {
        ruleForm,
        rules,
        ruleFormRef,
        submitForm,
        resetForm,
        storeLogin
      }
    }
  }
</script>

<style lang="less">
  .logDialog {
    .demo-ruleForm {
      width: 400px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      // background-color: beige;
    }
  }
</style>
